//
//  TabBarView.swift
//  Box
//
//  Created by mn on 2025/3/28.
//

import UIKit

class TabBarView: UIView {
    
    var onTabSelected: ((Int) -> Void)?
    var shouldSelectTab: ((Int) -> Bool)?

    private lazy var firstButton = TabButton(title: "商城", imageName: "tabbar_mall")
    private lazy var secondButton = TabButton(title: "仓库", imageName: "tabbar_stash")
    private lazy var thirdButton = TabButton(title: "我的", imageName: "tabbar_mine")
    
    private let stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .center
        return stackView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        addSubview(stackView)
        layer.cornerRadius = 28
        layer.masksToBounds = true
        backgroundColor = .darkGrayCustom
        
        firstButton.setSelected(true)
        [firstButton, secondButton, thirdButton].enumerated().forEach { index, button in
            button.tag = index
            button.addTarget(self, action: #selector(tabButtonTapped(_:)), for: .touchUpInside)
            stackView.addArrangedSubview(button)
        }
        
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    func select(at index: Int) {
        [firstButton, secondButton, thirdButton].forEach { button in
            button.setSelected(button == firstButton)
        }
    }
    
    @objc private func tabButtonTapped(_ sender: TabButton) {

        guard shouldSelectTab?(sender.tag) ?? true else { return }
        onTabSelected?(sender.tag)

        [firstButton, secondButton, thirdButton].forEach { button in
            button.setSelected(button == sender)
        }
    }
}
